package cn.com.oceansoft.oauth.server.biz.validator;

import cn.com.oceansoft.oauth.server.biz.service.IOAuthClientsService;
import cn.com.oceansoft.oauth.server.biz.entity.OAuthClients;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by BEN on 2016/4/19.
 */
@Component
public class OAuthClientsValidator implements Validator {

    @Autowired
    private IOAuthClientsService oauthService;

    @Override
    public boolean supports(Class<?> clazz) {
        return OAuthClients.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        OAuthClients oAuthClients = (OAuthClients) target;

        validateClientId(oAuthClients, errors);
        validateClientSecret(oAuthClients, errors);
    }


    private void validateClientSecret(OAuthClients oAuthClients, Errors errors) {
        final String clientSecret = oAuthClients.getClientSecret();
        if (StringUtils.isEmpty(clientSecret)) {
            errors.rejectValue("clientSecret", null, "client_secret is required");
            return;
        }

        if (clientSecret.length() < 8) {
            errors.rejectValue("clientSecret", null, "client_secret 长度至少8位");
        }
    }

    private void validateClientId(OAuthClients oAuthClients, Errors errors) {
        final String clientId = oAuthClients.getClientId();
        if (StringUtils.isEmpty(clientId)) {
            errors.rejectValue("clientId", null, "client_id is required");
            return;
        }

        if (clientId.length() < 5) {
            errors.rejectValue("clientId", null, "client_id 长度至少5位");
            return;
        }

        OAuthClients oAuthClients1 = oauthService.loadOauthClients(clientId);
        if (oAuthClients1 != null) {
            errors.rejectValue("clientId", null, "client_id [" + clientId + "] 已存在");
        }

    }
}
